# -*- coding: utf-8 -*-

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.process
from tornado.options import define, options

from apps import configs
from apps.plugins.customsql import CustomSQL
from apps.plugins.cachedata import CacheData

from apps.services.cache import CacheAction
from apps.log import Logger
from apps.services.Alarm import AlarmModel
from apps.services.Device import DeviceModel
from apps.services.User import UserModel
from apps.plugins.email import EmailQueue
from apps.plugins.sms import SmsQueue
from apps.urls import urls
define('port', type=int, default=8395)

Logger.init()


class Application(tornado.web.Application):

    def __init__(self):
        settings = dict(debug=False, )
        # 初始化数据库表
        self.db = CustomSQL(configs.MYSQL)
        self.user_model = UserModel(self.db)
        self.device_model = DeviceModel(self.db)
        self.alarm_model = AlarmModel(self.db)
        # 初始化缓存
        self.cache = CacheData(configs.REDIS).connect()
        self.cache_action = CacheAction(self.cache)
        tornado.web.Application.__init__(self, urls, **settings)


def make_app():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    loop = tornado.ioloop.IOLoop.current()
    loop.spawn_callback(EmailQueue.start)
    loop.spawn_callback(SmsQueue.start)
    loop.start()
    
if __name__ == '__main__':
    make_app()
